using UnityEngine;
using System.Collections;

public class MeleeMove : MonoBehaviour {
	//-- properties --//
	/**
	 * Enemy movement speed.
	 **/
	public const float xDelta = -10f;
	
	/**
	 * Distance player must be within for a move/shoot update to occur
	 **/
	public float xDistToActivate = 15;
	// TODO move to some public const?
	
	private bool isRight = false;
	private bool isLeft = false;
	
	public Animator anim;
	float animSpeed= 0;
	
	
	//-- MeleeMove methods --//
	// Use this for initialization
	void Start () {
		// ....
	}
	
	// Update is called once per frame
	void Update () {
		// find distance
		GameObject player = GenerateObjects.getPlayer();
		if (player == null) {
			print ( "null player" );
			return;
		}
		
		Vector3 playerPosition = player.transform.position;
		float diff = playerPosition.x - this.transform.position.x;
		
		// which side is player?
		isRight = diff < 0;
		isLeft = diff > 0;
		
		if (isRight) {
			diff *= -1;
		}
		
		// are we hit?
		
		
		if (this.GetComponent<TakeMuliHits>().timesShot == 0 && diff > xDistToActivate) {
			// kill updates on distance units?
			animSpeed= Mathf.Lerp(animSpeed, 0, Time.deltaTime * 2);	
			anim.SetFloat("Run", animSpeed);
			return;	
		}
		
		// actual move
		if (isRight) {
			transform.Translate( Vector3.right * (xDelta * Time.deltaTime) );
		}
		if (isLeft) {
			transform.Translate( Vector3.left * (xDelta * Time.deltaTime) );
		}
		animSpeed= Mathf.Lerp(animSpeed, 10, Time.deltaTime * 2);	
		anim.SetFloat("Run", animSpeed);
		
		// TODO jumps and avoidance?
	}
	
	/**
	 * Handles collisions
	 **/
	void OnCollisionEnter (Collision collisionInfo ) {
		GameObject weHit = collisionInfo.gameObject;
		
		// did we hit the player?
		if (GenerateObjects.getPlayer() == weHit.gameObject) {
			GenerateObjects.getPlayer().GetComponent<CharacterManager>().respawn();
			
			// TODO particles
			Destroy( this.gameObject );
		}
		
		
	}
}
